package com.css.prompt.service;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.css.prompt.model.Model;
import com.css.prompt.repository.ModelRepository;

@Service
public class ModelService {

    private final ModelRepository modelRepository;

    public ModelService(ModelRepository modelRepository) {
        this.modelRepository = modelRepository;
    }

    public List<Model> getAllModels() {
        return modelRepository.findAll();
    }

    public Optional<Model> getModelById(Long id) {
        return modelRepository.findById(id);
    }

    public Model createModel(Model model) {
    	model.setLastTested(LocalDate.now());
    	model.setCreatedAt(LocalDate.now());
        return modelRepository.save(model);
    }

    public Model updateModel(Long id, Model updatedModel) {
        return modelRepository.findById(id)
                .map(existingModel -> {
                    existingModel.setName(updatedModel.getName());
                    existingModel.setIdentifier(updatedModel.getIdentifier());
                    existingModel.setDescription(updatedModel.getDescription());
                    existingModel.setApiUrl(updatedModel.getApiUrl());
                    existingModel.setApiKey(updatedModel.getApiKey());
                    existingModel.setDefaultSearch(updatedModel.getDefaultSearch());
                    existingModel.setStatus(updatedModel.getStatus());
                    existingModel.setLastTested(LocalDate.now());
                    return modelRepository.save(existingModel);
                })
                .orElseThrow(() -> new RuntimeException("Model not found"));
    }

    public void deleteModel(Long id) {
        modelRepository.deleteById(id);
    }
    
    public Model toggleStatus(Long id) {
    	Model model = modelRepository.findById(id).orElseThrow(() -> new RuntimeException("模型不存在"));
        if ("Active".equalsIgnoreCase(model.getStatus())) {
            model.setStatus("Disabled");
        } else {
            model.setStatus("Active");
        }
        return modelRepository.save(model);
    }
    
    public Page<Model> getPage(Pageable pageable) {
        return modelRepository.findAll(pageable);
    }

    public Page<Model> searchByName(String name, Pageable pageable) {
        return modelRepository.findByNameContainingIgnoreCase(name, pageable);
    }
}

